package com.xinzhidi.web.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import org.springframework.stereotype.Component;

/***
 * @author cx
 * @date 2023/5/26 10:35
 */
@Component
public class WsServer {


    /**
     * 单例静态内部类
     */
    public static class SingletionWServer {
        static final WsServer instance = new WsServer();
    }

    public static WsServer getInstance() {
        return SingletionWServer.instance;
    }

    private EventLoopGroup mainGroup;
    private EventLoopGroup subGroup;
    private ServerBootstrap server;
    private ChannelFuture future;

    public static int port = 9195;

    public WsServer() {
        mainGroup = new NioEventLoopGroup();
        subGroup = new NioEventLoopGroup();
        server = new ServerBootstrap();
        server.group(mainGroup, subGroup)
                .channel(NioServerSocketChannel.class);
//                .childHandler(new WsServerInitialzer());//添加自定义初始化处理器
    }

    public void start() {
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();

        try {
            // 初始化ServerBootstrap实例， 此实例是netty服务端应用开发的入口
            ServerBootstrap bootstrap = new ServerBootstrap();
            // 把两个线程组加入进来 初始化的主从"线程池"
            bootstrap.group(boss, worker);
            // 指定使用NioServerSocketChannel这种类型通道  由于是服务端，故而是NioServerSocketChannel
            bootstrap.channel(NioServerSocketChannel.class);
            // 一定要使用去绑定具体的事件处理器
            bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    ChannelPipeline pipeline = socketChannel.pipeline();
                    pipeline.addLast(new ByteArrayEncoder());
                    pipeline.addLast(new ByteArrayDecoder());
                    pipeline.addLast(new SocketHandler());
                }
            });
            // 默认128
            bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
            // 配置子通道也就是SocketChannel的选项
            bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
            bootstrap.childOption(ChannelOption.TCP_NODELAY, true);

            // 绑定并侦听某个端口
            ChannelFuture future = bootstrap.bind(port).sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }

        //===============
//        future = this.server.bind(9194);
//        System.err.println("netty 服务端启动完毕 .....");
    }
}
